<script setup lang="ts">
import { onMounted, ref, nextTick, h, reactive } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import commonSearch from "./commonSearch.vue";
import JsonViewer from "@/components/jsonVewer/index.vue";
import { getAssetTotal } from "../servers";
import {
  getAssetList,
  deleteAsset,
  deleteTag,
  addTag,
  getAssetDetail,
  getAssetChangelog,
} from "../servers";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { Clock, Right } from "@element-plus/icons-vue";

const props = defineProps<{
  task: string;
}>();

const assetList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogData = ref({});
const activeTab = ref("basic");

// 标签编辑相关状态
const editingRowId = ref(null);
const newTagValue = ref("");
const tagInputRef = ref();
const changelogList = ref([]);

const columns = ref<TableColumn[]>([
  {
    label: "域名",
    prop: "domain",
    minWidth: 180,
    show: true,
    render: (row: any) => {
      return h(
        "a",
        {
          href: `https://${row.domain}`,
          target: "_blank",
          style: {
            color: "#409eff",
            textDecoration: "underline",
          },
        },
        row.domain
      );
    },
  },
  {
    label: "IP地址",
    prop: "ip",
    width: 150,
    show: true,
  },
  {
    label: "端口",
    prop: "port",
    width: 80,
    align: "center",
    show: true,
  },
  {
    label: "服务",
    prop: "service",
    width: 100,
    align: "center",
    show: true,
  },
  {
    label: "时间",
    prop: "time",
    width: 180,
    show: true,
  },
  {
    label: "类型",
    prop: "type",
    width: 100,
    align: "center",
    show: true,
  },
  {
    label: "状态",
    prop: "status",
    width: 80,
    align: "center",
    show: true,
    render: (row: any) => {
      if (row.status === null) {
        return "未知";
      }
      return row.status;
    },
  },
  {
    label: "标题",
    prop: "title",
    minWidth: 120,
    show: true,
    render: (row: any) => {
      return row.title || "-";
    },
  },
  {
    label: "TAG",
    prop: "tags",
    minWidth: 120,
    show: true,
    slot: "tags",
  },
  {
    label: "Banner",
    prop: "banner",
    minWidth: 200,
    show: true,
    render: (row: any) => {
      if (!row.banner) return "-";
      // 截取前50个字符显示
      return row.banner.length > 50
        ? row.banner.substring(0, 50) + "..."
        : row.banner;
    },
  },
  {
    label: "应用/组件",
    prop: "products",
    minWidth: 150,
    show: true,
    slot: "products",
  },
  {
    label: "标签",
    prop: "tags",
    width: 120,
    show: true,
    render: (row: any) => {
      if (!row.tags || row.tags.length === 0) return "-";
      return row.tags.join(", ");
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 150,
    fixed: "right",
    align: "center",
    show: true,
    slot: "action",
  },
]);

const formData = ref({
  search: "",
});

const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 处理查看详情
const handleViewDetail = async (row: any) => {
  const { data } = await getAssetDetail({ id: row.id });
  const { data: changelog } = await getAssetChangelog({ id: row.id });
  changelogList.value = changelog;
  console.log(changelog, "changelogList");
  dialogData.value = data;
  dialogVisible.value = true;

  // 模拟完整的资产数据
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteAsset({ ids: [row.id], index: "asset" });
    ElMessage.success("删除成功");
    getPageData();
  });
};

const getPageData = async () => {
  let params: any = {
    ...formData.value,
    pageIndex: pagination.currentPage,
    pageSize: pagination.pageSize,
  };
  if (props.task) {
    params.filter = {
      task: [props.task],
    };
  }
  const { data } = await getAssetList({ data: params, type: "asset" });
  const { data: total } = await getAssetTotal({ ...params, index: "asset" });
  assetList.value = data.list;
  pagination.total = total.total;
};

onMounted(() => {
  getPageData();
});

const handleSearch = (v: any) => {
  // console.log(v, "formData");
  getPageData();
};

const handleSearchReset = () => {
  // 重置表单数据
  formData.value = {
    search: "",
  };
  pagination.currentPage = 1;
  getPageData();
};

// 点击添加标签按钮
const handleAddTag = async (row: any) => {
  editingRowId.value = row.id;
  newTagValue.value = "";

  // 等待DOM更新后聚焦输入框
  await nextTick();
  if (tagInputRef.value) {
    tagInputRef.value.focus();
  }
};

// 输入框失去焦点时触发
const handleTagBlur = async (row: any) => {
  const trimmedValue = newTagValue.value.trim();

  if (trimmedValue) {
    // 确保row.tags是数组
    if (!row.tags) {
      row.tags = [];
    }

    // 检查标签是否已存在
    if (!row.tags.includes(trimmedValue)) {
      // row.tags.push(trimmedValue);
      // console.log("添加标签成功:", trimmedValue, "到行:", row);
      try {
        await addTag({ id: row.id, tp: "asset", tag: trimmedValue });
        ElMessage.success("添加标签成功");
        getPageData();
      } catch (error) {
        ElMessage.error("添加标签失败");
      }
    } else {
      console.log("标签已存在:", trimmedValue);
    }
  }

  // 重置编辑状态
  editingRowId.value = null;
  newTagValue.value = "";
};

// 按下回车键时也触发添加
const handleTagKeydown = (event: Event, row: any) => {
  const keyboardEvent = event as KeyboardEvent;
  if (keyboardEvent.key === "Enter") {
    handleTagBlur(row);
  } else if (keyboardEvent.key === "Escape") {
    // 按ESC键取消编辑
    editingRowId.value = null;
    newTagValue.value = "";
  }
};

const handleDeleteTag = async (row: any, tag: string) => {
  console.log("删除标签:", row, tag);
  try {
    await deleteTag({ id: row.id, tp: "asset", tag: tag });
    ElMessage.success("删除标签成功");
    getPageData();
  } catch (error) {
    ElMessage.error("删除标签失败");
  }
};

const handlePaginationChange = (page: number) => {
  pagination.currentPage = page;
  getPageData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getPageData();
};

// 判断是否为JSON字符串
const isJsonString = (str: string): boolean => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
};

// 格式化JSON字符串
const formatJson = (jsonString: string): string => {
  try {
    const parsed = JSON.parse(jsonString);
    return JSON.stringify(parsed, null, 2);
  } catch (e) {
    return jsonString;
  }
};
</script>

<template>
  <commonSearch
    v-model="formData"
    @search="handleSearch"
    @reset="handleSearchReset"
  />
  <div style="height: 10px"></div>
  <el-card>
    <DynamicTable
      :pagination="pagination"
      :columns="columns"
      :data="assetList"
      :loading="loading"
      @current-page-change="handlePaginationChange"
      @size-change="handleSizeChange"
    >
      <template #action="{ row }">
        <el-button type="primary" size="small" @click="handleViewDetail(row)">
          详情
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
      </template>
      <template #products="{ row }">
        <el-tag
          v-for="product in row.products"
          :key="product"
          type="success"
          size="small"
          style="margin-right: 4px; margin-bottom: 2px"
        >
          {{ product }}
        </el-tag>
        <span v-if="!row.products || row.products.length === 0">-</span>
      </template>
      <template #tags="{ row }">
        <el-tag
          v-for="tag in row.tags"
          @close="handleDeleteTag(row, tag)"
          closable
          :key="tag"
          type="success"
        >
          {{ tag }}
        </el-tag>

        <!-- 编辑状态：显示输入框 -->
        <el-input
          v-if="editingRowId === row.id"
          ref="tagInputRef"
          v-model="newTagValue"
          size="small"
          placeholder="输入标签名称"
          style="width: 120px; margin-left: 4px"
          @blur="handleTagBlur(row)"
          @keydown="handleTagKeydown($event, row)"
        />

        <!-- 非编辑状态：显示添加按钮 -->
        <el-button
          v-else
          type="default"
          size="small"
          @click="handleAddTag(row)"
          style="margin-left: 4px"
        >
          + addTag
        </el-button>
      </template>
    </DynamicTable>
  </el-card>
  <el-dialog v-model="dialogVisible" title="详情" width="840px">
    <div>
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="原始数据" name="basic">
          <JsonViewer :data="dialogData" height="450px" />
        </el-tab-pane>
        <el-tab-pane label="资产变更" name="scan">
          <div class="changelog-container">
            <div v-if="changelogList.length === 0" class="empty-state">
              <el-empty description="暂无资产变更记录" />
            </div>
            <el-timeline v-else class="changelog-timeline">
              <el-timeline-item
                v-for="(changelog, index) in changelogList"
                :key="index"
                :timestamp="changelog.timestamp"
                placement="top"
                :icon="Clock"
                color="#409eff"
              >
                <div class="changelog-item">
                  <div class="changelog-header">
                    <h4 class="changelog-title">资产变更记录</h4>
                    <el-tag size="small" type="info">{{
                      changelog.assetid
                    }}</el-tag>
                  </div>

                  <div class="changes-list">
                    <div
                      v-for="(change, changeIndex) in changelog.change"
                      :key="changeIndex"
                      class="change-item"
                    >
                      <div class="change-header">
                        <span class="field-name">{{ change.fieldname }}</span>
                        <el-tag size="small" type="warning">字段变更</el-tag>
                      </div>

                      <div class="change-content">
                        <div class="change-section">
                          <h5 class="change-label">旧值</h5>
                          <div class="change-value old-value">
                            <pre
                              class="code-block"
                              v-if="isJsonString(change.old)"
                              >{{ formatJson(change.old) }}</pre
                            >
                            <pre class="code-block" v-else>{{
                              change.old
                            }}</pre>
                          </div>
                        </div>

                        <div class="change-arrow">
                          <el-icon><Right /></el-icon>
                        </div>

                        <div class="change-section">
                          <h5 class="change-label">新值</h5>
                          <div class="change-value new-value">
                            <pre
                              class="code-block"
                              v-if="isJsonString(change.new)"
                              >{{ formatJson(change.new) }}</pre
                            >
                            <pre class="code-block" v-else>{{
                              change.new
                            }}</pre>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
// 标签样式
:deep(.el-tag) {
  margin-right: 4px;
  margin-bottom: 2px;
}

// 标签输入框样式
:deep(.el-input.is-small .el-input__inner) {
  height: 24px;
}

// 资产变更样式
.changelog-container {
  max-height: 600px;
  overflow-y: auto;
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.changelog-timeline {
  margin-top: 20px;

  :deep(.el-timeline-item__wrapper) {
    padding-left: 20px;
  }

  :deep(.el-timeline-item__timestamp) {
    font-size: 14px;
    color: #909399;
    font-weight: 500;
  }
}

.changelog-item {
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.changelog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.changelog-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.changes-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.change-item {
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  padding: 16px;
}

.change-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.field-name {
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
  background: #ecf5ff;
  padding: 4px 8px;
  border-radius: 4px;
}

.change-content {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.change-section {
  flex: 1;
  min-width: 0;
}

.change-label {
  font-size: 12px;
  font-weight: 600;
  color: #606266;
  margin: 0 0 8px 0;
  text-transform: uppercase;
}

.change-value {
  border-radius: 4px;
  overflow: hidden;

  &.old-value {
    border-left: 3px solid #f56c6c;
  }

  &.new-value {
    border-left: 3px solid #67c23a;
  }
}

.code-block {
  background: #282c34;
  color: #abb2bf;
  padding: 12px;
  border-radius: 4px;
  font-family: "Courier New", Courier, monospace;
  font-size: 12px;
  line-height: 1.5;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  max-height: 200px;
  overflow-y: auto;
}

.change-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 16px;
  margin-top: 20px;
  flex-shrink: 0;
}

// 响应式设计
@media (max-width: 768px) {
  .change-content {
    flex-direction: column;
    gap: 12px;
  }

  .change-arrow {
    margin-top: 0;
    transform: rotate(90deg);
  }

  .changelog-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>
